<template>
  <div>
    <input type="text" placeholder="请输入车辆信息" v-model="title" />
    <div class="div">
      <el-button type="success" size="small" @click="exportExcel"
        ><i class="el-icon-share"></i> 导出</el-button
      >
    </div>
    <el-table id="table" style="width: 100%" height="20rem" :data="tableData">
      <el-table-column
        :label="title + '车辆' + prevDate + '到' + nextDate + '新增故障'"
        align="center"
      >
        <template v-for="(item, i) of tableHead">
          <el-table-column
            :prop="item"
            :label="item"
            align="center"
            :key="i"
            width="350"
          ></el-table-column>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { mapState } from 'vuex'
import xlsxStyle from 'xlsx-style'
// import { XSU } from '../../static/xlsxStyle.utils'
export default {
  data() {
    return {
      tableHead: [],
      tableData: [],
      prevDate: [],
      nextDate: [],
      title: '',
    }
  },
  methods: {
    //定义导出Excel表格事件
    exportExcel() {
      this.$nextTick(() => {
        let xlsxParam = { raw: true }
        let wb = XLSX.utils.table_to_book(
          document.querySelector('#table'),
          xlsxParam
        )
        this.setExlStyle(wb['Sheets']['Sheet1'])
        /* 获取二进制字符串作为输出 */
        let wbout = xlsxStyle.write(wb, {
          bookType: 'xlsx',
          bookSST: true,
          type: 'buffer',
        })
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: 'application/octet-stream' }),
            //设置导出文件名称
            `${this.title}车辆${this.prevDate}到${this.nextDate}新增故障.xlsx`
          )
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      })
    },
    // 设置导出的excel文件的文字对齐和列宽
    setExlStyle(data) {
      data['!cols'] = [{ wpx: 350 }, { wpx: 350 }, { wpx: 350 }]
      console.log(data)
      for (let key in data) {
        if (data[key] instanceof Object) {
          data[key].s = {
            alignment: {
              horizontal: 'center', //水平居中对齐
              vertical: 'center',
            },
            font: {
              // 设置
              sz: 14,
            },
            bold: true,
            numFmt: 0,
          }
        }
      }
      return data
    },
    // 当allObj数据发生改变时，对tableData初始化，更新导出内容
    setTableData() {
      if (this.allObj.length !== 0) {
        let prevFalut = this.allObj[0].prev
        let nextFault = this.allObj[0].next
        let newAddFault = this.allObj[0].newAdd
        this.prevDate = this.allObj[0].prevDate
        this.nextDate = this.allObj[0].nextDate
        this.tableHead = [this.prevDate, this.nextDate, '新增']
        let max = Math.max(
          prevFalut.length,
          nextFault.length,
          newAddFault.length
        )
        this.tableData = []
        for (var i = 0; i < max; i++) {
          let tempObj = {}
          this.tableData.push(tempObj)
        }
        // 取出每个tableData中的对象，并初始化tableData
        let a = this.prevDate
        let b = this.nextDate
        for (var j = 0; j < max; j++) {
          prevFalut[j] && (this.tableData[j][a] = prevFalut[j])
          nextFault[j] && (this.tableData[j][b] = nextFault[j])
          newAddFault[j] && (this.tableData[j]['新增'] = newAddFault[j])
        }
      } else {
        this.$message({
          type: 'success',
          message: '数据导出结束',
        })
      }
    },
    shiftAllObj() {
      setTimeout(() => {
        if (this.allObj.length !== 1) {
          this.allObj.shift()
        }
      }, 100)
    },
  },
  computed: {
    ...mapState(['allObj']),
  },
  watch: {
    allObj() {
      if (this.allObj) {
        // 当数据发生改变的时候，对数据进行处理
        this.setTableData()
        // 页面更新之后导出内容
        this.exportExcel()
        this.shiftAllObj()
        // 当数据处理完成之后，开始加载界面
        // this.$nextTick(() => {
        //   // 页面更新完成之后导出excel
        //   this.exportExcel()
        //   // 开启一个定时器删除this.allObj的第一个元素
        //   setTimeout(() => {
        //     if (this.allObj.length !== 0) {
        //       this.allObj.shift()
        //     }
        //   }, 100)
        // })
      }
    },
  },
}
</script>

<style lang="css" scoped>
.div {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 0.5rem;
}
/*滚动条的宽度*/
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
/*滚动条滑块*/
/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}
</style>
